using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
	[Header("Config")]
	[SerializeField] private float speed;

	private PlayerAnimations playerAnimations;
	private PlayerActions actions;
	private Player player;
	private Rigidbody rb;
	
	private Vector2 moveDirection;
	private Vector2 lastDirection;

   
	private void Awake()
	{
		playerAnimations = GetComponent<PlayerAnimations>();
		player = GetComponent<Player>();
		actions = new PlayerActions();
		rb = GetComponent<Rigidbody>();
	}

	void Start()
	{
		
	}

   
	void Update()
	{
		ReadMovement();
	}

	private void FixedUpdate()
	{
		Move();
	}

	private void Move()
	{
		if (player.Stats.health <= 0f) return;
		
		Vector3 position = rb.position;
		position.x += moveDirection.x * speed * Time.fixedDeltaTime;
		position.z += moveDirection.y * speed * Time.fixedDeltaTime;
		rb.MovePosition(position);
	}

	private void ReadMovement()
	{
		moveDirection = actions.Movement.Move.ReadValue<Vector2>().normalized;

		if (moveDirection != lastDirection)
		{
			if (moveDirection != Vector2.zero)
			{
				playerAnimations.SetMoveAnimation(moveDirection);
			}
			playerAnimations.SetMoveBoolTransition(moveDirection != Vector2.zero);
		}

		lastDirection = moveDirection;
	}

	private void OnEnable()
	{
		actions.Enable();
	}

	private void OnDisable()
	{
		actions.Disable();
	}
}
